package com.mi.easyexceldemo.utils;

import com.mi.easyexceldemo.constants.ComConstants;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;

public class FileUtil {

    private static final String SEPARATOR = ".";

    /**
     * 上传文件
     *
     * @param uploadPath 上传文件夹路径
     * @param file 文件
     * @return 上传文件路径
     */
    public static String uploadFile(String uploadPath, MultipartFile file) throws Exception {
        File folderPath = new File(uploadPath);
        //判断文件路径下的文件夹是否存在，不存在则创建
        if (!folderPath.exists()) {
            folderPath.mkdirs();
        }
        String filePath = "";
        if (file != null) {
            filePath =
                    folderPath.getAbsolutePath() + "/" + UUID.randomUUID() + file.getOriginalFilename();
            file.transferTo(new File(filePath));
        }
        return filePath;
    }

    /**
     * 删除文件
     */
    public static void deleteFile(String filePath) {
        if (null != filePath && StringUtils.isNotBlank(filePath)) {
            File file = new File(filePath);
            if (file.exists() && file.isFile()) {
                file.delete();
            }
        }
    }

    /**
     * 下载文件
     */
    public static void downloadFile(HttpServletRequest request, HttpServletResponse response,
                                    String path, String downloadName) throws FileNotFoundException {

        InputStream is = null;
        OutputStream os = null;
        File file = new File(path);
        String ext = StringUtils.substringAfter(file.getName(), SEPARATOR);
        try {
            is = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            is.close();
            // 清空response
            response.reset();
            response.setContentType("application/octet-stream");
            // 兼容不同浏览器下导出文件名显示中文
            String agent = request.getHeader("USER-AGENT");
            // firefox
            if (agent != null && agent.toLowerCase().contains(ComConstants.BROWSER_TYPE_FIREFOX)) {
                String enableFileName = "=?UTF-8?B?" + (new String(
                        Base64.encodeBase64((downloadName + SEPARATOR + ext).getBytes("UTF-8"))))
                        + "?=";
                response.setHeader("Content-Disposition", "attachment; filename=" + enableFileName);
            } else {
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder
                        .encode(downloadName, "UTF-8") + SEPARATOR + ext);
            }
            os = new BufferedOutputStream(response.getOutputStream());
            os.write(buffer);
            os.flush();
            os.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}